var ue;
$(function () {


    //简介符文版框
    ue = UE.getEditor('container', {
        initialContent: "在此填写简介@-@",
        enableAutoSave: false,
        pasteplain: true,
        toolbars: [
            [ 'source', 'undo', 'redo', 'bold']
        ],
        autoHeightEnabled: true,
        autoFloatEnabled: true
    });

    $('#add').click(function () {
        $("#from_word_info").trigger("reset");
        add();
    });

    $('#update').click(function () {
        // 获取选中行信息
        var row = $('#table').bootstrapTable('getSelections');
        if (row == null || "" == row) {
            swal({
                title: "初始化失败!",
                text: "请选择行!",
                type: "error",
                confirmButtonText: "确定"
            });
        } else {
            edit(row[0]);
        }
    });

    $('#del').click(function () {
        // 获取选中行信息
        var row = $('#table').bootstrapTable('getSelections');
        if (row == null) {
            swal({
                title: "删除失败!",
                text: "请选择行!",
                type: "error",
                confirmButtonText: "确定"
            });
        } else {
            swal({
                title: "确定到删除",
                text: "确定要删除该行，删除后将无法回复",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                closeOnConfirm: false,
                closeOnCancel: true
            }, function (isConfirm) {
                if (isConfirm) {
                    del(row[0].id);
                }
            });

        }
    });


    // 文件初始化
    $('#fileupload').fileinput({
        language: 'zh', // 设置语言
        uploadUrl: '../../common/upload/upPic.json', // 上传的地址
        allowedFileExtensions: ['jpg', 'png', 'gif'],// 接收的文件后缀
        showUpload: true, // 是否显示上传按钮
        maxFileCount: 1,
        maxFileSize: 20000,
        enctype: 'multipart/form-data',
        showCaption: false,// 是否显示标题
        browseClass: "btn btn-primary", // 按钮样式
        layoutTemplates: {
            actionDelete: '',
            actionUpload: '',
            actionZoom: '',
            actionDrag: ''
        },
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",


    }).on("fileuploaded", function (event, data) {
        if (data.response) {
            //alert('处理成功'+data.response.data.list[0].uri);
            // if ($('#pic_input').val() == "" || $('#pic_input').val() == undefined) {

                $('#pic_input').val(data.response.data.list[0].uri);
            // } else {
            //     var pic_ali = $('#pic_input').val();
            //     pic_ali = pic_ali + "," + data.response.data.list[0].uri;
            //     $('#pic_input').val(pic_ali);
            // }
        }
    });


    $(document).on("click", ".fileinput-remove", function () {
        $("#pic_input").val(null);
    });


    // 加载数据
    $('#table')
        .bootstrapTable(
            {
                url: '../../wordMainAction/main.json',
                pagination: true,
                // height: 470,
                method: 'POST', //请求方式（*）
                contentType: "application/x-www-form-urlencoded",
                dataType: "json",
                pageSize: 10,
                pageList: [10, 20, 30],
                sidePagination: 'server',// 设置为服务器端分页
                pageNumber: 1,
                striped: true, // 是否显示行间隔色
                search: true, // 显示搜索框
                toolbar: '#toolbar', // 工具按钮用哪个容器
                sortable: true, // 是否启用排序
                showToggle: true,
                showColumns: true,
                showRefresh: true, // 是否显示刷新按钮
                selectItemName: 'btSelectItem',
                showExport: true, advancedSearch: true,
                idForm: 'form_search',
                actionForm: 'main.json',
                Locales: {
                    formatAdvancedSearch: '查询',
                    formatAdvancedCloseButton: '关闭'
                },
                idTable: 'table_search',
                uniqueId: "id",
                exportDataType: 'basic',
                clickToSelect: true, // 选择行即选择checkbox
                singleSelect: true, // 仅允许单选
                strictSearch: true,
                columns: [
                    {
                        align: 'center',
                        width: 50,
                        checkbox: true
                    },
                    {
                        field: 'id',
                        title: '编号',
                        align: 'center',
                        width: 15,
                        sortable: true
                    },
                    {
                        field: 'wordName',
                        title: '词条名',
                        align: 'center',
                        sortable: true
                    },
                    {
                        field: 'wordImg',
                        title: '词条举例图片',
                        align: 'center',
                        formatter: function (value, row, index) {
                            var html = "<img alt='777' src='"
                                + value
                                + "' style='width:50px;height:50px;'>";
                            return html;
                        }

                    },
                    {
                        field: 'wordIntroduction',
                        title: '词条简介',
                        align: 'center',
                        sortable: true
                    },
                    {
                        field: 'createTime',
                        title: '创建时间',
                        align: 'center',
                        sortable: true
                    }
                ]

            });


});

$('#btn_add').click(function () {
    if (!$('#from_word_info').valid()) {
        lrError("请输入必填项！");
        return;
    }
    var index = layer.load(0, {
        shade: false
    });
    $.ajax({
        type: "POST",
        url: "../../wordMainAction/add.json",
        dataType: "json",
        data: $("#from_word_info").serialize(),
        success: function (data) {
            layer.closeAll('page');
            layer.close(index);
            emptyForm($('#from_word_info'));
            swal({
                title: "添加成功!",
                text: "用户添加成功!",
                type: "success",
                confirmButtonText: "确定"
            });
        },
        error: function () {
            layer.close(index);
            lrError("添加失败！服务器错误！");
        }
    });
});

$('#btn_update').click(function () {
    if (!$('#from_word_info').valid()) {
        lrError("请输入必填项！");
        return;
    }
    var index = layer.load(0, {
        shade: false
    });
    $.ajax({
        type: "POST",
        url: "../../wordMainAction/update.json",
        dataType: "json",
        data: $("#from_word_info").serialize(),
        success: function (data) {
            swal({
                title: "修改!",
                text: "修改成功!",
                type: "success",
                confirmButtonText: "确定"
            });
            layer.closeAll('page');
            layer.close(index);
        },
        error: function () {
            layer.close(index);
            lrError("添加失败！服务器错误！");
        }
    });
});

// 删除
function del(id) {

    var index = layer.load(0, {
        shade: false
    });
    $.ajax({
        type: "POST",
        url: "../../wordMainAction/del.json",
        dataType: "json",
        data: {
            "id": id
        },
        success: function (data) {
            $('#table').bootstrapTable('refresh');
            swal({
                title: "删除",
                text: "删除成功!",
                type: "success",
                confirmButtonText: "确定"
            });
            layer.close(index);

        },
        error: function () {
            lrError("删除失败！服务器错误！");
            layer.close(index);
        }
    });
}

// 添加操作
function add() {
    $("#btn_update").hide();
    $("#btn_add").show();
    var index_main = layer.open({
        type: 1,
        title: '添加',
        shadeClose: true,
        shade: false,
        maxmin: true, // 开启最大化最小化按钮
        area: ['75%', '85%'],
        content: $('#div_word_info'),
        end: function () { // 此处用于演示
            $('#table').bootstrapTable('refresh');
        }
    });

    $('#btn_close').click(function () {
        layer.close(index_main);
    });

}


// 修改操作

function edit(row) {
    bindForm('from_word_info', row);
    $("#btn_add").hide();
    $("#btn_update").show();

    ue = UE.getEditor('container', {
        initialContent: row.wordIntroduction,
        enableContextMenu: false,
        autoHeightEnabled: false,
        initialFrameHeight: 480
    });

    var u = row.wordImg;
    $('#fileupload').fileinput('destroy');
    $('#fileupload').fileinput({
        language: 'zh', // 设置语言
        initialPreviewDelimiter: ",",
        initialPreview: u,

        initialPreviewAsData: true,
        // deleteUrl: "url/url",
        // deleteExtraData:,
        initialPreviewFileType: 'image',
        uploadUrl: '../../common/upload/upPic.json', // 上传的地址
        allowedFileExtensions: ['jpg', 'png', 'gif'],// 接收的文件后缀
        showUpload: true, // 是否显示上传按钮
        maxFileCount: 1,
        maxFileSize: 20000,
        layoutTemplates: {
            //**
            actionUpload: '',
            actionZoom: '',
            actionDrag: ''
        },

        enctype: 'multipart/form-data',
        showCaption: false,// 是否显示标题
        browseClass: "btn btn-primary", // 按钮样式
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",


    }).on("fileuploaded", function (event, data) {
        if (data.response) {
            //alert('处理成功'+data.response.data.list[0].uri);
            // if ($('#pic_input').val() == "" || $('#pic_input').val() == undefined) {

                $('#pic_input').val(data.response.data.list[0].uri);
            // } else {
            //     var pic_ali = $('#pic_input').val();
            //     pic_ali = pic_ali + "," + data.response.data.list[0].uri;
            //     $('#pic_input').val(pic_ali);
            // }
        }
    });


    var index_main = layer.open({
        type: 1,
        title: '修改信息',
        shadeClose: true,
        shade: false,
        maxmin: true, // 开启最大化最小化按钮
        area: ['75%', '85%'],
        content: $('#div_word_info'),
        end: function () { // 此处用于演示
            // swal("添加成功!", "活动信息保存成功", "success");
            $('#table').bootstrapTable('refresh');

        }
    });

    $('#btn_close').click(function () {
        layer.close(index_main);
    });

}

function refreshTable() {
    $('#table').bootstrapTable('refresh');
}
